//
//  ViewController.swift
//  CooperSwift
//
//  Created by CooperSwiftappkf@163.com on 04/26/2021.
//  Copyright (c) 2021 CooperSwiftappkf@163.com. All rights reserved.
//

import UIKit
import CooperSwift
//import WCDBSwift
import Cooper_BGFMDB
import RxSwift
import JXSegmentedView
import Then
import HandyJSON
import ZLPhotoBrowser
import SKPhotoBrowser

import PredicateFlow
import swiftScan
import Toast_Swift
import SwiftUI
import SwiftyContacts

// 点击事件
class ViewControllerBaseVM: NSObject {
    
    let bag = DisposeBag()
    
    let items = [
        ("name", "method"),
        ("rows", "rowsTap"),
        ("changeTheme", "changeThemeTap"),
        ("wcdbTest", "wcdbTestTap"),
        ("autoTable", "autoTableTap"),
        ("tableCollectionShow", "tableCollectionShowTap"),
        ("imagesShow", "imagesShowTap"),
        ("formTable", "formTableTap"),
        ("yoga", "yogaTap"),
        ("stack", "stackTap"),
        ("rxALearning", "rxALearningTap"),
        ("rxBLearning", "rxBLearningTap"),
        ("rxCLearning", "rxCLearningTap"),
        ("rxDLearning", "rxDLearningTap"),
        ("rxTable", "rxTableTap"),
        ("rxMVVM", "rxMVVMTap"),
        ("swiftAVC", "swiftAVCTap"),
        ("deferTest", "deferTestTap"),
        ("loginVC", "loginVCTap"),
        ("testPage", "testPageTap"),
        ("listPage", "listPageTap"),
        ("collectionPage", "collectionPageTap"),
        ("loginTap", "loginTapTap"),
        ("register", "registerTap"),
        ("sourceTable", "sourceTableTap"),
        ("photoPick", "photoPickTap"),
        ("photoShow", "photoShowTap"),
        ("qrCode", "qrCodeTap"),
        ("qqScan", "qqScanTap"),
        ("reactorKit", "reactorKitTap"),
        ("flutter", "flutterTap"),
        ("flutterTwo", "flutterTwoTap"),
        ("refresh", "refreshTap"),
        ("pull", "pullTap"),
        ("net", "netTestTap"),
        ("toast", "toastTap"),
        ("screenshot", "screenshotTap"),
        ("cvView", "cvViewTap"),
        ("contacts", "contactsTap")
    ]
    
    @objc func rowsTap() {
        pushTo(TestTableRowsVC())
    }
    @objc func netTestTap() {
        APIUseDemo.formDataTest(bag)
    }
    
    @objc func refreshTap() {
        
    }
    
    
    @objc func pullTap() {
        
    }
    
    @objc func method() {
        debugPrint("method")
    }
    
    @objc func changeThemeTap() {
        ThemeManager.switchTheme(type: .blackTheme)
    }
    
    @objc func wcdbTestTap() {
//        pushTo(WCDBTestVC.self)
    }
    
    @objc func webTestTap() {
        let vc = BaseWKWebVC.init(urlStr: "https://m.910728.xyz/static/flutter/")
        vc.showSourceHint = true
        pushTo(vc)
    }
    
    @objc func autoTableTap() {
        let vc = RxDataSourceAutoTableVC()
        pushTo(vc)
    }
    
    @objc func tableCollectionShowTap() {
        let vc = TestCollectionShowTableVC()
        pushTo(vc)
    }
    
    @objc func imagesShowTap() {
        let vc = ImagesShowTableVC.init()
        pushTo(vc)
    }
    
    @objc func yogaTap() {
        pushTo(TestYogaCellVC.init())
    }
    
    @objc func stackTap() {
        pushTo(StackTestVC.init())
    }
    
    @objc func rxALearningTap() {
        pushTo(RxLearningAVC.init())
    }
    @objc func rxBLearningTap() {
        pushTo(RxLearningBVC.init())
    }
    @objc func rxCLearningTap() {
        pushTo(RxLearningCVC.init())
    }
    @objc func rxDLearningTap() {
        pushTo(RxLearningDVC.init())
    }
    
    @objc func rxTableTap() {
        pushTo(RxTableTestVC.init())
    }
    
    @objc func rxMVVMTap() {
        pushTo(RxMVVMTestVC())
    }
    
    @objc func swiftAVCTap() {
        pushTo(TestSwiftAVC())
    }
    
    @objc func deferTestTap() {
        pushTo(DeferTestVC.init())
    }
    
    @objc func loginVCTap() {
        pushTo(LoginVC.init())
    }
    
    @objc func formTableTap() {
        pushTo(TestFormTableVC.init())
    }
    
//    @objc func toastTap() {
//        ToastHelper.shared.showTextToast("x喜羊羊xx喜羊羊xx喜羊羊xx喜羊羊xx喜羊羊xx喜羊羊xx喜羊羊xx喜羊羊xx喜羊羊x")
//    }
    
    @objc func requestTap() {
//        MaoLingProvider.rx.request(.appIosversionGetlatestapkinfo).asObservable().mapHandyResultModel(type: ResultModel.self, toast: .all, tag: "xxx").asObservable().mapHandyModel(type: AppDataModel.self).subscribe(onNext: { [weak self] in
//            $0.apply{ appData in
//                self?.testBT.setTitle(appData.userId, for: .normal)
//            }
//        }).disposed(by: disposeBag)
    }
    
    @objc func testPageTap() {
        let titles = ["猴哥", "青蛙王子", "旺财", "粉红猪", "喜羊羊", "黄焖鸡", "小马哥", "牛魔王", "大象先生", "神龙"]
        let vc = JXPageBaseVC()
        vc.title = "itemTitle"
        //配置数据源
        let dataSource = JXSegmentedTitleDataSource()
        dataSource.isTitleColorGradientEnabled = true
        dataSource.titles = titles
        vc.segmentedDataSource = dataSource
        //配置指示器
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorWidth = 20
        vc.segmentedView.indicators = [indicator]
        pushTo(vc)
    }
    
    @objc func listPageTap() {
        pushTo(TestListPageVC())
    }
    
    @objc func collectionPageTap() {
        pushTo(TestCollectionPageVC())
    }
    
    @objc func loginTapTap() {
        pushTo(XOHLoginVC())
    }
    
    @objc func registerTap() {
        pushTo(XOHRegisterVC())
    }
    
    @objc func sourceTableTap() {
        pushTo(RxDataSourceTableVC())
    }
    
    @objc func photoPickTap() {
//        guard let vc = self.serviceBlock!(.controller) as? UIViewController else { return }
//        let ps = ZLPhotoPreviewSheet()
//        ps.selectImageBlock = { [weak self] (images, assets, isOriginal) in
//
//        }
//        ps.showPhotoLibrary(sender: vc)
    }
    
    @objc func photoShowTap() {
        var images = [SKPhoto]()
        for i in 320...330 {
            let photo = SKPhoto.photoWithImageURL("https://dss1.bdstatic.com/kvoZeXSm1A5BphGlnYG/skin_zoom/\(i).jpg")
            photo.shouldCachePhotoURLImage = false // you can use image cache by true(NSCache)
            images.append(photo)
        }
        let browser = SKPhotoBrowser(photos: images)
        browser.initializePageIndex(0)
        presentTo(browser)
    }
    
    @objc func qrCodeTap() {
        pushTo(QRCodeVC())
    }
    
    @objc func qqScanTap() {
        pushTo(QQScanViewController())
    }
    
    @objc func reactorKitTap() {
        let vc = ReactorKitTestVC.init()
        vc.reactor = ProfileViewReactor()
        pushTo(vc)
    }
    
    @objc func flutterTap() {
//        let flutterEngine = (UIApplication.shared.delegate as! AppDelegate).flutterEngine
//        let vc = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
//        vc.sh_prefersNavigationBarHidden = true
//        pushTo(vc)
    }
    
    @objc func flutterTwoTap() {
//        let flutterViewController = FlutterViewController(project: nil, nibName: nil, bundle: nil)
//        presentTo(flutterViewController, animated: true, completion: nil)
    }
    
    @objc func cvViewTap() {
        pushTo(TestCollectionVPageVC())
    }
    
//    @objc func contactsTap() {
//
//    }
    
//    @available(iOS 15.0.0, *)
    @objc func contactsTap() {
        AuthCheckHandler.shared.hw_openContactsServiceWithBlock(true) {
            if $0 {
                pushTo(ContactUserSelectVC())
            }
        }
        
//        pushTo(ContactUserSelectVC())
        
//        do {
//            Task {
//                let access = try await requestAccess()
//                debugPrint(access)
//            }
////            return access
//        }catch {
//            print(error)
////            return false
//        }
//
//        let status = authorizationStatus()
//        print(status == CNAuthorizationStatus.authorized)
//
//        do {
//            Task {
//                let contacts = try await fetchContacts()
//                debugPrint(contacts)
//            }
////            return access
//        }catch {
//            print(error)
////            return false
//        }
    }
    
}

// MARK: - table 实现
class ViewControllerModel: NSObject, TableCellConfigProtocol {
    
    var model: Any?
    
    required init(_ model: Any?) {
        self.model = model
    }
    
    func cellCls() -> UITableViewCell.Type {
        return ViewControllerCell.self
    }
    
}

class ViewControllerVM: ViewControllerBaseVM, TableViewModelProtocol, UITableViewDelegate {
    
    func configDown() {
        var array = Array<ViewControllerModel>()
        for item in items {
            array.append(
                ViewControllerModel(item)
            )
        }
        addFirstSectionItems(array)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let info = self.item(indexPath: indexPath)
        guard let target = info as? ViewControllerModel else { return }
        guard let arr = target.model as? (String, String) else { return }
        let sel = Selector(arr.1)
        if let vc = self.serviceBlock!(.controller) as? ViewController {
            if vc.responds(to: sel)  {
                vc.perform(sel, with: arr)
            }
        }
        if responds(to: sel)  {
           perform(sel, with: arr)
        }
    }
 
}


//class ViewController: UIViewController, TableEnableProtocol, SelfAware {
//
//    static func awake() {
//        debugPrint("🧵🧵🧵awake🧵🧵🧵")
//    }
//
//    let disposeBag = DisposeBag()
//
//    let vm = ViewModelFactory.tableVM(ViewControllerVM.self)
//
//    var observable: Observable<String>!
//
//    override func viewDidLoad() {
//        super.viewDidLoad()
//
////        var empty = EmptyDataSetConfigure()
////        empty.tipStr = "暂无数据"
////        empty.tipImage = UIImage(named: "settings")
////        EmptyDataSetableConfigure.setDefaultEmptyDataSetConfigure(empty)
//
////        switchV.rx.value.bind(to: UIApplication.shared.rx.isNetworkActivityIndicatorVisible).disposed(by: disposeBag)
//
//        configAll(vm, disposeBag: disposeBag)
//
//        tableView.snp.updateConstraints { make in
//            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
//        }
//
//    }
//
//    /// 截图
//    @objc func screenshotTap() {
////        let imgV = UIImageView.init(image: view.screenshotTap())
////        guard let image = tableView.contentScreenshot() else { return }
//        guard let image = tableView.tableContentScreenshot() else { return }
//        let imgV = UIImageView.init(image: image).then {
//            $0.contentMode = .scaleToFill
//        }
//        imgV.frame = CGRect(0, 0, view.frame.width/3.0, view.frame.height/2.0)
//        view.showViewToast(imgV, tap:true)
//    }
//
//    /// 吐司
//    @objc func toastTap() {
//        print(self.view.frame)
//        let contentV = TestToastContentV.loadFromNib()
//        contentV.frame = CGRect(0, 0, 220, 220)
//        view.showViewToast(contentV, tap: false, position: .bottomNoPadding)
//        let contentV1 = TestToastContentV.loadFromNib()
//        contentV1.frame = CGRect(0, 0, 220, 220)
//        view.showViewToast(contentV1, tap: false, position: .center)
//        let contentV2 = TestToastContentV.loadFromNib()
//        contentV2.frame = CGRect(0, 0, 220, 220)
//        view.showViewToast(contentV2, tap: false, position: .topNoPadding)
////        view.showToast(contentV, duration: 3000000, position: .center) {
////            debugPrint($0)
////        }
////        ToastHelper.shared.showTextToast("ViewController")
////        ToastHelper.shared.showTextToast("ViewController")
////        ToastHelper.shared.showTextToast("ViewController")
//    }
//
//    override func didReceiveMemoryWarning() {
//        super.didReceiveMemoryWarning()
//        // Dispose of any resources that can be recreated.
//    }
//
//}

extension ViewController: QRRectDelegate {
    func drawwed() {
        
    }
}


extension Array where Element: Comparable {
    
    func findSmallItems(_ v: Element, _ nums: inout [Element]){
        for item in self {
            if item < v {
                nums.append(item)
            }
        }
    }
    
}

// MARK: - collection page

class ViewController: UIViewController, CollectionEnableProtocol, Refreshable {
    
    let bag = DisposeBag()

    let vm = ViewModelFactory.collectionVM(ViewControllerCollectionVM.self)
    
//    let btn = UIButton.init(type: .custom).then {
//        $0.frame = CGRect(0, 0, Screen.width, 44)
//        $0.setTitle("获取验证码", for: .normal)
//        $0.setTitleColor(.gray, for: .normal)
//        $0.backgroundColor = .green
//    }
 
    override func viewDidLoad() {
        super.viewDidLoad()
        
        BGDB.shareManager().debug = true
        
        let bgChildFmdb = TestBGFMDBSqliteModel()
        bgChildFmdb.name = "子"
        bgChildFmdb.id = 2
        
        
        let bgParentFmdb = TestBGFMDBSqliteModel()
        bgParentFmdb.name = "父"
        bgParentFmdb.id = 1
        bgParentFmdb.model = bgChildFmdb
        
        bgParentFmdb.bg_saveOrUpdate()
        
        TestBGFMDBSqliteModel.bg_findAll(nil)?.forEach({ tmp in
            guard let info = tmp as? TestBGFMDBSqliteModel  else { return }
            if let bg_result = TestBGFMDBSqliteModel.bg_find(nil, where: " where \(bg_sqlKey("name"))=\(bg_sqlValue(info.name!))") {
                debugPrint(bg_result.first ?? "xx")
            }
        })
        
        let layout = UICollectionViewLeftAlignedLayout()
        layout.minimumLineSpacing = 0.01;
        layout.minimumInteritemSpacing = 0.01;
        layout.itemSize  = CGSize((Screen.width - 0.1)/4.0, (Screen.width - 0.1)/4.0)
        configAll(vm, disposeBag: bag, refreshConfig: .header, edges: UIEdgeInsets(top: 0, left: 0, bottom: Screen.bottomBarHeight, right: 0), flowLayout: layout)
        
        
        navigationItem.rightBarButtonItems = UIBarButtonItem.barItems(texts: ["按钮1", "按钮2"], method: { sender in
            debugPrint(sender.titleLabel?.text ?? "")
        })
        
//        view.addSubview(btn)
//        btn.addTarget(self, action: #selector(tap(_:)), for: .touchUpInside)
        
        
//        sh_prefersNavigationBarHidden = true
        
//    case url /// 地址
//    case email /// 邮箱
//    case letter /// 只能输入由26个英文字母组成的字符串
//
//    case idCard /// 身份证件
//    case password /// 密码
//    case nickname /// 昵称
    }
    
    
    @objc func tap(_ btn: UIButton) {
        btn.countdown(second: 5, bag: bag)
    }
    
}

// UICollectionViewLeftAlignedLayout  UICollectionViewDelegateFlowLayout
class ViewControllerCollectionVM: ViewControllerBaseVM, CollectionViewModelProtocol, UICollectionViewDelegateFlowLayout, RefreshControllable {
    
    func configDown() {
        toState(.loading)
        refresh()
    }
    
    func refresh() {
        print("refresh")
        PublicMethod.delay(0.5) {
            
            var array = Array<ViewControllerCollectionModel>()
            for item in self.items {
                array.append(
                    ViewControllerCollectionModel(item)
                )
            }
            self.addFirstSectionItems(array)
            
            self.rx.refreshStatus.onNext(.endHeaderRefresh)
            self.rx.refreshStatus.onNext(.showFooter)
            
            self.toState(.noData)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let info = self.item(indexPath: indexPath)
        guard let target = info as? ViewControllerCollectionModel else { return }
        guard let arr = target.model as? (String, String) else { return }
        let sel = Selector(arr.1)
        if let vc = self.serviceBlock!(.controller) as? ViewController {
            if vc.responds(to: sel)  {
                vc.perform(sel, with: arr)
            }
        }
        if responds(to: sel)  {
           perform(sel, with: arr)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return vm_collectionView(collectionView, layout: collectionViewLayout, sizeForItemAt: indexPath)
    }
    
}


class ViewControllerCollectionModel: NSObject, CollectionCellConfigProtocol {
        
    func cellCls() -> UICollectionViewCell.Type {
        return ViewControllerCVC.self
    }
    
    var model: Any?
    
    required init(_ model: Any?) {
        super.init()
        self.model = model
        self.cellSize = CGSize(Screen.width/4.0 - 0.01, 66)
    }
    
}
